package com.d16_Socket_Homework.homework1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ServerDemo1_UDP {
    public static void main(String[] args) throws IOException {
        //创建接收端DatagramSocket对象，指定接受的端口号
        DatagramSocket ds = new DatagramSocket(11111);
        System.out.println("接收端显示：");
        while (true) {
            //创建数据包接收数据
            byte[] bytes = new byte[8192];
            DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
            //接收数据
            ds.receive(dp);
            //获取发送者IP
            InetAddress address = dp.getAddress();
            String host = "未知IP";
            if (address != null) {
                host = address.getHostAddress();
            }
            //解析数据包
            byte[] datas = dp.getData();
            String data = new String(datas, 0, datas.length);
            System.out.println(host + "说:" + data);
        }
    }
}
